package com.xu.cloud.common.advice;

import com.xu.cloud.common.constant.OrderConstant;
import com.xu.cloud.common.pojo.Result;
import com.xu.cloud.common.api.ApiContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 错误码错误信息设置后置通知处理器
 *
 * @author xuguan
 * @since 2025/1/14
 */
@Order(OrderConstant.ERROR_CODE_MSG_SETTING_ADVICE_ORDER)
@Slf4j
@RestControllerAdvice
public class ErrorCodeMsgSettingAdvice implements ResponseBodyAdvice<Result<?>> {

    private static final String ERROR_ATTRIBUTE = DefaultErrorAttributes.class.getName() + ".ERROR";

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return Result.class.isAssignableFrom(returnType.getParameterType());
    }

    @Override
    public Result<?> beforeBodyWrite(Result<?> body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        final ApiContext apiContext = ApiContext.current();
        if (Objects.nonNull(body)) {
            apiContext.setCode(body.getCode());
            apiContext.setMsg(body.getMsg());
        }

        if (request instanceof ServletServerHttpRequest) {
            final HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            final Exception exception = (Exception) servletRequest.getAttribute(ERROR_ATTRIBUTE);
            apiContext.setThrowable(exception);
        }

        return body;
    }
}
